package com.example.jimmerfast.util;

import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.babyfish.jimmer.sql.ast.query.ConfigurableRootQuery;
import org.babyfish.jimmer.sql.ast.table.Table;

import java.util.List;

public class JimmerUtil {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }
    public static <T> PageResult<T> page(PageParam pageParam, ConfigurableRootQuery<? extends Table<T>, T> query) {
        long total = query.count();
        List<T> records = query.limit(pageParam.getPageSize(), (pageParam.getCurrentPage() - 1) * pageParam.getPageSize()).execute();
        PageResult<T> scPageResult = new PageResult<>();
        scPageResult.setCurrentPage(pageParam.getCurrentPage());
        scPageResult.setPageSize(pageParam.getPageSize());
        scPageResult.setTotal(total);
        scPageResult.setRecords(records);
        return scPageResult;
    }


    @SneakyThrows
    public static <T> T objectToEntityUnloaded(Object object,Class<T> entityClass){
        ObjectMapper objectMapper = SpringUtil.getBean(ObjectMapper.class);
        String s = objectMapper.writeValueAsString(object);
        Object o = MAPPER.readValue(s, Object.class);
        String s1 = MAPPER.writeValueAsString(o);
        return objectMapper.readValue(s1, entityClass);
    }
}